<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var lowestCommonAncestor = function (root, p, q) {
        function postOrder(root) {
          //如果当前节点遍历到了p，q直接返回
          if (root == p || root == q || !root) return root
          let left = postOrder(root.left)
          let right = postOrder(root.right)

          //后序遍历想要left、right有值，必须return 一个节点
          if (left && right) {
            return root
          }
          if (left) {
            return left
          }
          if (right) {
            return right
          }
          //如果都没有，就return undefined
        }
        return postOrder(root)
      }

      let tree = {
        val: 1,
        left: {
          val: 2,
          left: {
            val: 4
          },
          right: {
            val: 5
          }
        },
        right: {
          val: 3,
          right: {
            val: 7
          }
        }
      }
      /* 后序遍历处理中节点逻辑 */
      function postOrder(root) {
        if (!root) return root
        let left = postOrder(root.left)
        let right = postOrder(root.right)
        //这个left是保存的是当前root节点的左子树的返回值！！！
        if (root.val == 2) {
          console.log(left) //即节点4
        }
        return root
      }
    </script>
  </body>
</html>
